package com.chenl.provider.DEMOS;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;

@Slf4j
@SpringBootTest
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class sendEmail {
    private final JavaMailSender javaMailSender;

    //1.普通文字内容邮件
    @Test
    void sendEmailTest01() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("这是一封测试邮件");
        message.setFrom("2219343558@qq.com");
        message.setTo("2219343558@qq.com");
        message.setSentDate(new Date());
        message.setText("这是测试邮件的正文");
        javaMailSender.send(message);
    }

    //带附件邮件(发送的文件都以附件形式存在)
    @Test
    void sendEmailTest02() throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject("这是一封测试邮件2");
        helper.setFrom("2219343558@qq.com");
        helper.setTo("2219343558@qq.com");
        helper.setSentDate(new Date());
        helper.setText("这是测试邮件的正文");
//        helper.addAttachment("一些需要记录的东西.txt", new File("D://files/abc.txt"));
        helper.addAttachment("test.jpg", new File("D://files/test.jpg"));
        helper.addAttachment("sfz.jpg", new File("D://files/sfz.jpg"));
        javaMailSender.send(mimeMessage);
    }

    //正文带图片的邮件(图片直接嵌套在内容中)
    @Test
    void sendEmailTest03() throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject("这是一封测试邮件3");
        helper.setFrom("2219343558@qq.com");
        helper.setTo("2219343558@qq.com");
        helper.setSentDate(new Date());
        helper.setText("<p>肥猪的一封测试邮件，这封邮件包含两种图片，分别如下</p><p>第一张图片：</p><img src='cid:p01'/><p>第二张图片：</p><img src='cid:p02'/>", true);
        helper.addInline("p01", new FileSystemResource(new File("D://files/test.jpg")));
        helper.addInline("p02", new FileSystemResource(new File("D://files/sfz.jpg")));
        javaMailSender.send(mimeMessage);
    }
}
